package org.springframework.roo.addon.graph.support;

import org.springframework.roo.addon.graph.GraphProvider;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.process.manager.MutableFile;
import org.springframework.roo.project.Path;
import org.springframework.roo.project.PathResolver;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.TemplateUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Scanner;

/**
 * @author Michael Hunger
 * @since 28.08.2010
 */
public class
        PersistenceXmlUpdater {
    private final PathResolver pathResolver;
    private final FileManager fileManager;

    public PersistenceXmlUpdater(final PathResolver pathResolver, final FileManager fileManager) {
        this.pathResolver = pathResolver;
        this.fileManager = fileManager;
    }

    private String getPath() {
        return pathResolver.getIdentifier(Path.SRC_MAIN_RESOURCES, "META-INF/persistence.xml");
    }


    public void update(final GraphProvider graphProvider, final String dataStoreLocation) {
        final String path = getPath();
        final boolean persistenceExists = fileManager.exists(path);
        if (persistenceExists) throw new IllegalStateException("persistence.xml already exists, won't overwrite");

        fileManager.createOrUpdateTextFileIfRequired(path, readTemplateContents(),true);
    }

    private String readTemplateContents() {
        InputStream templateInputStream = null;
        try {
            templateInputStream = TemplateUtils.getTemplate(getClass(), "persistence.xml");
            Assert.notNull(templateInputStream, "Could not acquire persistence.xml template");
            return new Scanner(templateInputStream).useDelimiter("\\Z").next();
        } finally {
            if (templateInputStream != null) try {
                templateInputStream.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}
